生成矩阵X1和X2,两者随机从[-10,10]内整数中抽取10个样本,且形状分别为2 $\times$ 5和5 $\times$ 2,随机种子分别为0和1,输出结果;
将X1和X2的转置用两种方法实现按行合并,分别赋值给Xnew1和Xnew2,输出结果,并比较结果的差异;
对矩阵X1实现按行求和和按列求和;
计算X1 $\times$ X2;
生成矩阵X,两者随机从[-10,10]内整数中抽取25个样本,形状为5 $\times$ 5,随机种子为0,同时生成向量y=[3,2,4,6,1],求解$X\beta=y$的方程解;
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
import numpy as np
#第一题
np.random.seed(0)
X1=np.random.randint(-10,10,(2,5))
np.random.seed(0)
X2=np.random.randint(-10,10,(5,2))
print(X1)
print(X2)
#第二题
Xnew1=np.concatenate((X1,X2.T))
Xnew2=np.stack((X1,X2.T))
print(Xnew1.ndim,Xnew2.ndim)
print(Xnew1,"\n\n",Xnew2)
#发现输出后Xnew1是拼接而成的,输入2维数组返回2维数组;Xnew2是堆叠形成的,输入2维返回3维
#第三题
print("Row sums:",X1.sum(axis=1)) #按行求和
print("Column sums:",X1.sum(axis=0)) #按列求和
#第四题
print("X1*X2为\n",np.matmul(X1,X2))
print("X1*X2为\n",X1@X2) #另一种方式
#第五题
np.random.seed(0)
X=np.random.randint(-10,10,(5,5))
y=np.array([3,2,4,6,1])
np.linalg.solve(X,y)
shops_nm.xlsx文档里面记录了有关火锅店铺的基本信息,包括点名,评分,菜品等。
把shops_nm.xlsx读入到数据框raw_data中, 输出其列名, 行数和列数大小, 前五行的内容;
挑选出数据框raw_data中评价数不缺失的行,挑选出的数据赋值给数据框raw_data2,输出行数, 列数以及前五行的内容;
对于数据框raw_data2,利用apply函数以及自定义函数clean_price(x)(函数作用为去除字符串x中的中文内容)去除"人均"列中的所有中文字符,并该列数据格式转化为浮点型数据,输出raw_data2前五行的内容;
对于数据框raw_data2,新建一列数据,列名为"商家等级", 若'评分'<=2,商家等级为0,若2<'评分'<=3.5,商家等级为1,其余'评分'的商家等级为2,输出raw_data2前五行的内容;
对于数据框raw_data2,根据'关键词'和'商家等级'分组计算平均评分,并输出结果;
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
import pandas as pd
#第一题
raw_data=pd.read_excel("shops_nm.xlsx")
raw_data.head(n=5) #输出前五行
raw_data.shape #行列数
print(raw_data.columns) #列名
#第二题
raw_data2=raw_data[raw_data["评价数"].isnull()==False]
raw_data2.shape
raw_data2.head(n=5)
#第三题
import warnings
warnings.filterwarnings("ignore")
def clean_price(x):
filter_words=['人均:',"人均","大概","左右","差不多"]
if type(x) is int or type(x) is float:
return x
for word in filter_words:
if word in x:
x=x.replace(word,"")
return x
raw_data2["人均"]=raw_data2["人均"].apply(clean_price)
raw_data2["人均"]=raw_data2["人均"].astype(float)
raw_data2.head(n=5)
# 改动了一下自定义函数
def clean_price(x):
filter_words=['人均:',"人均","大概","左右","差不多"]
if type(x) is int or type(x) is float:
return float(x)
for word in filter_words:
if word in x:
x=x.replace(word,"")
return x
raw_data2["人均"]=raw_data2["人均"].apply(clean_price)
raw_data2.head(n=5)
#第四题
import warnings
warnings.filterwarnings("ignore")
def cate_shops(x):
if x <= 2: return 0
elif x <=3.5: return 1
else: return 2
raw_data2['商家等级'] = raw_data2['评分'].apply(cate_shops)
raw_data2.head()
#第五题
raw_data2.groupby(by=['关键词','商家等级']).agg({'评分':'mean'})
将merge_shop_coupon_nm.xls读入到数据框merge_data中, 输出其列名, 行数和列数大小, 前五行的内容;
设置全局中文字体为'SimHei';
设置画布大小为(15,10),绘制如下四幅子图,第一幅子图展示人均评价关系图,第二幅子图展示人均评价关系局部图,评价数截取500-6500之间,人均截取20-60,第三幅子图按关键词分组绘制人均评价关系局部图,截取范围与第二幅子图类似,第四幅绘制购买人数评价数目关系图,购买人数和评价数绘图范围都截取0-3000;
设置画布大小为(10,5),绘制如下纵向排列和横向排列的直方图;
设置画布大小为(10,8),绘制如下反映购买人数评价数关系的箱型图
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt # 导入Matplotlib中的画图函数pyplot,命名为plt
#第一题
merge_data=pd.read_excel("merge_shop_coupon_nm.xls")
merge_data.head(n=5) #输出前五行
merge_data.shape #行列数
print(merge_data.columns) #列名
#第二题
import matplotlib
matplotlib.rcParams['font.sans-serif']=['SimHei']
matplotlib.rcParams['axes.unicode_minus']=False
#第三题
import warnings
warnings.filterwarnings("ignore")
import matplotlib
matplotlib.rcParams['font.sans-serif']=['SimHei']
matplotlib.rcParams['axes.unicode_minus']=False
fig=plt.figure(figsize=(15,10))
# 创建子图
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)
ax1.set_title("人均评价关系图")
ax1.set_xlabel("人均")
ax1.set_ylabel("评价数")
ax1.scatter(x=merge_data["人均"], y=merge_data["评价数"], color="r", marker='v')
ax2.set_title("人均评价关系局部图")
ax2.set_xlabel("人均")
ax2.set_ylabel("评价数")
ax2.scatter(x=merge_data["人均"], y=merge_data["评价数"], color="r", marker='v')
ax2.set_xlim(20,60)
ax2.set_ylim(500,6500)
ax2.hlines(2000, 20, 60, colors="r", linestyle="dashed")
ax3.set_title("人均评价关系局部图")
ax3.set_xlabel("人均")
ax3.set_ylabel("评价数")
ax3.scatter(x=merge_data["人均"][merge_data['关键词']=='火锅'], y=merge_data["评价数"][merge_data['关键词']=='火锅'], color="r", marker='v',label = '火锅')
ax3.scatter(x=merge_data["人均"][merge_data['关键词']!='火锅'], y=merge_data["评价数"][merge_data['关键词']!='火锅'], color="b", marker='o',label='非火锅')
ax3.legend(loc='upper left',bbox_to_anchor=(0,1))
ax3.set_xlim(20,60)
ax3.set_ylim(500,6500)
ax3.hlines(2000, 20, 60, colors="r", linestyle="dashed")
ax4.set_title("人数评价数目关系图")
ax4.set_xlabel("购买人数")
ax4.set_ylabel("评价数")
ax4.scatter(x=merge_data["购买人数"], y=merge_data["评价数"], color="r", marker='v')
ax4.plot(np.arange(3000), np.arange(3000), color='blue')
ax4.set_xlim(0,3000)
ax4.set_ylim(0,3000)
plt.show()
#第四题
fig=plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)
ax1.hist(merge_data['评分'],bins=30,color='r',rwidth=0.9)
ax2.hist(merge_data["评分"], bins=30, color="b", rwidth=0.9,cumulative = 'True', orientation = 'horizontal')
ax1.set_xlabel("评分")
plt.show()
#第五题
#画成下方所示图例
#数据预处理
d1 = merge_data["评价数"][merge_data["购买人数"] < 500]
d2 = merge_data["评价数"][merge_data["购买人数"] >= 500][merge_data["购买人数"] < 1000 ]
d3 = merge_data["评价数"][merge_data["购买人数"] >= 1000][merge_data["购买人数"] < 1500 ]
d4 = merge_data["评价数"][merge_data["购买人数"] >= 1500][merge_data["购买人数"] < 2000 ]
d5 = merge_data["评价数"][merge_data["购买人数"] >= 2000]
d = [d1, d2, d3, d4]#, d5]
#绘图
fig=plt.figure(figsize=(10,8))
ax = fig.add_subplot(1,1,1)
ax.boxplot(d,
patch_artist='Patch',
labels=['<500','[500,1000)','[1000,1500)','[1500,2000)'],
boxprops = {'color':'#2196F3','facecolor':'#BBDEFB'}
)
ax.set_title("购买人数评价数目关系图")
ax.set_xlabel("购买人数")
ax.set_ylabel("评价数")
plt.show()